package com.sxz.sbs.module.sale;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sxz.sbs.R;
import com.sxz.sbs.app.AppConstant;
import com.sxz.sbs.applibrary.component.ClearEditText;
import com.sxz.sbs.applibrary.state.StateLayout;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.constant.IntentConstant;
import com.sxz.sbs.constant.TypeConstant;
import com.sxz.sbs.event.OperateSuccessEvent;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.client.adapter.AllHousesAdapter;
import com.sxz.sbs.module.client.bean.AllHousesBean;
import com.sxz.sbs.module.staff.ChoseStaffActivity;
import com.sxz.sbs.module.staff.mode.StaffIntentBean;
import com.sxz.sbs.module.staff.presenter.AllHousesPresenter;
import com.sxz.sbs.module.staff.view.AllHousesView;
import com.sxz.sbs.router.RouterUrl;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class BuildingSearchActivity extends BaseActivity<AllHousesPresenter> implements AllHousesView {

    @BindView(R.id.cet_search_building)
    ClearEditText cetSearchBuilding;
    @BindView(R.id.rv_search_building)
    RecyclerView rvSearchBuilding;
    @BindView(R.id.state_building)
    StateLayout stateBuilding;
    private AllHousesAdapter adapter;
    private List<AllHousesBean.HousesBean> dataList = new ArrayList<>();
    /**
     * 默认从销控进来的
     */
    private int fromType;
    private StaffIntentBean staffBean;
    @Override
    protected void init() {
        Intent intent = getIntent();
        fromType = intent.getIntExtra(TypeConstant.SEARCH_BUILDING_INTENT,0);
        if (fromType == 2) {
            staffBean = getIntent().getParcelableExtra("staff_bean");
        }
        rvSearchBuilding.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AllHousesAdapter(dataList);
        rvSearchBuilding.setAdapter(adapter);
        cetSearchBuilding.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    InputMethodManager imm = (InputMethodManager) v.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    if (TextUtils.isEmpty(cetSearchBuilding.getInputValue())) {
                        ToastUtils.showShort("搜索内容不能为空");
                        return false;
                    }
                    getSearchData();
                    return true;
                }
                return false;
            }
        });
        rvSearchBuilding.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (fromType) {
                    case TypeConstant.SALE_SEARCH_BUILDING:
                        ARouter.getInstance().build(RouterUrl.SALE_CONTROL_STALL)
                                .withString(IntentConstant.SALE_CONTROL_BUILD_NAME,dataList.get(position).getName())
                                .withInt(IntentConstant.SALE_CONTROL_BUILD_ID,dataList.get(position).getId())
                                .navigation();
                        break;
                    //  案场间调换
                    case 2:
                        staffBean.setSwapParkingId(dataList.get(position).getId());
                        staffBean.setParkingName(dataList.get(position).getName());
                        startActivity(new Intent(BuildingSearchActivity.this,ChoseStaffActivity.class)
                                .putExtra("staff_bean",staffBean)
                                .putExtra("chose_tag", ChoseStaffActivity.CHOSE_STAFF_SWAP_OUT)
                        );
                        break;
                    //  楼盘搜
                    case 3:
                        staffBean.setSwapParkingId(dataList.get(position).getId());
                        staffBean.setParkingName(dataList.get(position).getName());
                        startActivity(new Intent(BuildingSearchActivity.this,ChoseStaffActivity.class)
                                .putExtra("staff_bean",staffBean)
                                .putExtra("chose_tag", ChoseStaffActivity.CHOSE_STAFF_SWAP_OUT)
                        );
                        break;
                    case 5:
                        EventBus.getDefault().post(new OperateSuccessEvent());
                        Intent intent = new Intent();
                        intent.putExtra("parking_id",dataList.get(position).getId());
                        intent.putExtra("parking_name",dataList.get(position).getName());
                        setResult(1006,intent);
                        finish();
                        break;
                    default:
                        break;
                }
            }
        });
        stateBuilding.setOnRetryListener(new StateLayout.OnRetryListener() {
            @Override
            public void onRetry(int state) {
                getSearchData();
            }
        });
    }

    /**
     * 获取搜索数据
     */
    public void getSearchData () {
        HashMap<String,Object> map = HttpParamMap.getParamMap();
        map.put("txt", cetSearchBuilding.getInputValue());
        map.put("pageNumber", 1);
        map.put("pageSize", 20);
        mPresenter.getAllHouses(map,true);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_building_search;
    }

    @Override
    protected AllHousesPresenter createPresenter() {
        return new AllHousesPresenter();
    }

    @OnClick(R.id.tv_search_building_cancel)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onGetHousesDataSuccess(AllHousesBean bean) {
        if (mIsLive) {
            if (bean != null && bean.getList().size() > 0) {
                dataList.clear();
                dataList.addAll(bean.getList());
                adapter.notifyDataSetChanged();
            } else {
                stateBuilding.showEmpty();
            }
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOperateSuccessEvent(OperateSuccessEvent event) {
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Override
    public void showError(int errorTag, String msg) {
        if (errorTag == AppConstant.NET_ERROR_CODE) {
            stateBuilding.showNetwork();
        } else {
            stateBuilding.showEmpty();
        }
    }

    @Override
    public void loginAgain() {
        super.loginAgain();
        adapter.loadMoreComplete();
    }
}
